package cn.janyd.jmall.dubbo.core.filter;

import cn.janyd.common.core.vo.CommonResult;
import cn.janyd.jmall.dubbo.constants.I18nConstants;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;

import java.util.Locale;

/**
 * @author janyd
 * @since 2020/8/5 18:36
 */
@Activate(group = CommonConstants.PROVIDER, order = -1000)
public class DubboProviderI18nFilter implements Filter, Filter.Listener {

    private MessageSourceAccessor messageSourceAccessor;


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        //填充
        final Object value = appResponse.getValue();
        if (value instanceof CommonResult) {
            CommonResult<?> result = (CommonResult<?>) value;
            if (!result.isSuccess()) {
                String lang = RpcContext.getContext().getAttachment(I18nConstants.LANG);
                Locale locale = new Locale(lang);
                try {
                    result.setMessage(this.messageSourceAccessor.getMessage(result.codeStr(), locale));
                } catch (NoSuchMessageException e) {
                    //ignore
                }
                appResponse.setValue(result);
            }
        }
    }

    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {

    }

    public void setMessageSource(MessageSource messageSource) {
        this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
    }
}
